using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using MT.eVotePRS.Common;
using MT.eVotePRS.Device;
using MT.eVotePRS.Model;

namespace MT.eVotePRS.UI
{
    public partial class frmCheckOut : Form
    {   
        int displayCountDown;

        string handsetID;
        StudentInfo studentInfo;

        public frmCheckOut()
        {
            InitializeComponent();
            this.timer2.Start();

            Program.ArsAPIHelper.DataReceived += new ARSReceivedHandler(dataReceiver_DataReceived);
            
            timer1.Interval = 10 * 1000;
            displayCountDown = timer1.Interval/ 1000;

            handsetID = string.Empty;
            studentInfo = new StudentInfo();
        }

        protected override void WndProc(ref Message m)
        {
            int devCount;

            if (m.Msg == Device.Native.Win32Message.WM_DEVICECHANGE)
            {
                switch ((int)m.WParam)
                {
                    case Device.Native.Win32Message.DBT_DEVICEARRIVAL:
                    case Device.Native.Win32Message.DBT_DEVICEREMOVECOMPLETE:

                        devCount = Program.ArsAPIHelper.ArsDeviceConnected();

                        if (0 == devCount)
                        {
                            if (Program.ArsAPIHelper.Processing)
                            {
                                Program.ArsAPIHelper.StopProcess();
                            }
                            DialogBox.boxWarning(string.Format("Receiver Count={0}, Please prepare the receiver first.", devCount.ToString()), "Warning!");
                        }
                        Thread.Sleep(10);
                        break;
                    default:
                        break;
                }
            }
            base.WndProc(ref m);
        }

        void frmCheckOut_Load(object sender, EventArgs e)
        {
            this.txtDateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            
            // Since we are start this program, it would like to detect the device once.
            Message m = new Message();
            m.Msg = Device.Native.Win32Message.WM_DEVICECHANGE;
            m.WParam = (System.IntPtr)Device.Native.Win32Message.DBT_DEVICEARRIVAL;

            WndProc(ref m);

            int ret = Program.ArsAPIHelper.RegisterDeviceNotify((Int32)this.Handle);
            if (ret > 0)
            {
                Program.ArsAPIHelper.ClearReadBuffer();
            }

            Program.ArsAPIHelper.DataRegistered += new ARSRegisteredHandler(arsReceiver_HansetRegistry);
        }

        void frmCheckOut_FormClosing(object sender, FormClosingEventArgs e)
        {
            Program.ArsAPIHelper.StopProcess();

            Program.ArsAPIHelper.UnRegisterDeviceNotify();
        }

        void btnClose_Click(object sender, EventArgs e)
        {
            if (txtBarcode.Text != string.Empty
                || txtStudentNO.Text != string.Empty
                || txtStudentName.Text != string.Empty)
            {
                if (DialogBox.boxConfirmNo("Are you sure to abort the current action?") == DialogResult.No)
                    return;
            }

            this.Close();
            this.Dispose();
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            if (Program.ArsAPIHelper.Processing)
            {
                timer1.Stop();
                lblCountDown.Visible = false;

                Program.ArsAPIHelper.StopProcess();

                DialogBox.boxWarning("The Handset ID has not been input. Please try again.", "Warning!");

                txtBarcode.Enabled = true;
                btnConfirm.Enabled = true;
            }
        }

        void timer2_Tick(object sender, EventArgs e)
        {
            this.txtDateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

            if (Program.ArsAPIHelper.Processing)
            {
                displayCountDown --;
                lblCountDown.Text = displayCountDown.ToString();
            }
        }

        void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                studentInfo.Barcode = txtBarcode.Text.Trim();
                
                studentInfo.StudentNo = string.Empty;
                studentInfo.StudentName = string.Empty;
                txtStudentNO.Text = studentInfo.StudentNo;
                txtStudentName.Text = studentInfo.StudentName;

                txtIsGraduate.Text = studentInfo.IsGraduate.ToString();

                if ( ! string.IsNullOrEmpty( studentInfo.Barcode))
                {
                    if (!Common.Helper.Helper.IsNumeric(studentInfo.Barcode)
                        || (studentInfo.Barcode.Length < Constants.LEN_ID_Min || studentInfo.Barcode.Length > Constants.LEN_ID_Max))
                    {
                        DialogBox.boxWarning("Invalid Barcode!", "Warning!");
                        txtBarcode.SelectAll();
                        return;
                    }

                    if (Program.ArsAPIHelper.Processing)
                    {
                        this.timer1.Stop();
                        lblCountDown.Text = string.Empty;
                    }

                    try
                    {
                        StudentInfo checkedStudentInfo = new Presentation.Logic.StudentActions().FindStudentByBarcode(studentInfo.Barcode);
                        if (checkedStudentInfo != null)
                        {
                            studentInfo = checkedStudentInfo;
                            checkStudentAndStarReceiving();
                        }
                        else
                        {
                            DialogBox.boxWarning("The barcode is not found in system, please enter student No. to lookup.", "Warning!");

                            txtStudentNO.Focus();
                            txtStudentNO.SelectAll();
                        }
                    }
                    catch (Exception ex)
                    {
                        DialogBox.boxWarning("Exception: " + ex.Source + "; " + "Message: " + ex.Message, "Warning!");
                    }
                }
            }
        }

        void txtStudentNO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                studentInfo.StudentNo = txtStudentNO.Text.Trim();
                
                if ( string.IsNullOrEmpty(studentInfo.Barcode))
                {
                    DialogBox.boxWarning("Invalid Barcode!", "Warning!");
                    txtBarcode.Focus();
                    txtBarcode.SelectAll();
                    return;
                }
                if ( string.IsNullOrEmpty(studentInfo.StudentNo))
                {
                    DialogBox.boxWarning("Invalid Student ID!", "Warning!");
                    txtStudentNO.Focus();
                    txtStudentNO.SelectAll();
                    return;
                }
                
                if (studentInfo.Barcode == studentInfo.StudentNo)
                {
                    DialogBox.boxWarning("Barcode and Student No. entered must not be equivalent!", "Warning!");
                    studentInfo.Barcode = "";
                    studentInfo.StudentNo = "";
                    txtStudentNO.Text = studentInfo.StudentNo;
                    txtBarcode.Text = studentInfo.Barcode;

                    txtBarcode.Focus();
                    txtBarcode.SelectAll();
                    return;
                }

                if ( ! string.IsNullOrEmpty(studentInfo.StudentNo))
                {
                    if (!Common.Helper.Helper.IsNumeric(studentInfo.StudentNo) ||
                            studentInfo.StudentNo.Length < 8 || studentInfo.StudentNo.Length > 12)
                    {
                        DialogBox.boxWarning("Invalid Student ID!", "Warning!");
                        this.txtStudentNO.SelectAll();
                        return;
                    }

                    if (Program.ArsAPIHelper.Processing)
                    {
                        this.timer1.Stop();
                        Program.ArsAPIHelper.StopProcess();
                    }

                    try
                    {
                        StudentInfo checkStudentInfo = new Presentation.Logic.StudentActions().FindStudentByNo(studentInfo.StudentNo);
                        if (checkStudentInfo != null)
                        {
                            studentInfo = checkStudentInfo;

                            checkStudentAndStarReceiving();
                        }
                        else
                        {
                            DialogBox.boxWarning("The student No. is not found in system, please enter all student particulars and update to database", "Warning!");
                            
                            txtStudentName.Focus();
                            txtStudentName.SelectAll();
                            return;
                        }
                    }
                    catch(Exception ex)
                    {
                        DialogBox.boxWarning("Exception: " + ex.Source + "; " + "Message: " + ex.Message, "Warning!");
                    }
                }
            }
        }

        void txtStudentName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                studentInfo.StudentName = txtStudentName.Text.Trim();

                if (string.IsNullOrEmpty(studentInfo.Barcode))
                {
                    DialogBox.boxWarning("Invalid Barcode!", "Warning!");

                    txtBarcode.Focus();
                    txtBarcode.SelectAll();
                    return;
                }

                if (string.IsNullOrEmpty(studentInfo.StudentNo))
                {
                    DialogBox.boxWarning("Invalid Student ID!", "Warning!");

                    txtStudentNO.Focus();
                    txtStudentNO.SelectAll();
                    return;
                }

                if (studentInfo.Barcode == studentInfo.StudentNo)
                {
                    DialogBox.boxWarning("Barcode and Student No. entered must not be equivalent!", "Warning!");

                    txtBarcode.Focus();
                    txtBarcode.SelectAll();
                    return;
                }

                checkStudentAndStarReceiving();
            }
        }

        // Confirm to registry student id to handset
        void btnConfirm_Click(object sender, EventArgs e)
        {
            if (!IsValidate())
                return;

            if (studentInfo.Id < 1)
            {
                if (DialogBox.boxConfirmYes(@"No Record is found for the ""Barcode"", Save and Continue ?") != DialogResult.Yes)
                {
                    txtBarcode.Text = "";
                    txtStudentName.Text = "";
                    txtIsGraduate.Text = "";
                    txtStudentNO.Text = "";
                    txtHandsetID.Text = "";
                    txtRemark.Text = "";

                    txtBarcode.Enabled = true;

                    btnConfirm.Enabled = true;

                    return;
                }
            }

            // if handset is check out by another student 
            //  DialogBox.boxWarning("Check out failed! \r\n\r\nThe Handset had been Checked-out by another student!", "Warning!");
            // return

            
            timer1.Stop();
            btnConfirm.Enabled = false;
            displayCountDown = timer1.Interval / 1000;
            lblCountDown.Text = displayCountDown.ToString();
            lblCountDown.Visible = true;
            timer1.Start();

            // Start the fnWorkerThread to accept keypad press.
            Program.ArsAPIHelper.RegristerHandset(txtHandsetID.Text.Trim(), true);
            Thread.Sleep(100);
        }

        void SaveTxn()
        {
            try
            {
                if (studentInfo.Id < 1)
                {
                    //object objID = new Presentation.Logic.Students().CreateNewStudent();
                    //if (objID != null && Convert.ToInt32(objID) > 1)
                    //{
                    //    studentInfo.Id = Convert.ToInt32(objID);
                    //}
                    
                    //DialogBox.boxWarning("Student information can't be save!", "Warning!");

                    txtStudentNO.Text = "";
                    txtHandsetID.Text = "";
                    txtRemark.Text = "";
                    txtBarcode.Text = "";
                    txtStudentName.Text = "";
                    txtIsGraduate.Text = "";

                    return;
                }

                if (new Presentation.Logic.HandsetActions().CheckHandset(handsetID) == null)
                {
                    InventoryTable inventoryTable = new InventoryTable();
                    inventoryTable.HandsetID = handsetID;
                    inventoryTable.TxnTime = DateTime.Now;
                    inventoryTable.IsActive = true;

                    object inventTblID = new Presentation.Logic.HandsetActions().CreateNewHandset(inventoryTable);
                }


                InventoryTxn inventoryTxn = new InventoryTxn();
                inventoryTxn.HandsetID = handsetID;
                inventoryTxn.StudentID = studentInfo.StudentNo;
                inventoryTxn.TxnTime = DateTime.Now;
                inventoryTxn.Remark = txtRemark.Text;
                inventoryTxn.Status = Presentation.Util.Constants.Status_CheckOut.Id;
                inventoryTxn.UserEvent = Presentation.Util.Constants.Status_CheckOut.StatusDesc;
                inventoryTxn.NeedPay = false;
                inventoryTxn.PaymentNo = string.Empty;
                inventoryTxn.IsOverride = false;
                inventoryTxn.OverrideStatus = -1;

                object txnID = new Presentation.Logic.InventoryTxnActions().CreateNewTxn(inventoryTxn);
                if (txnID != null && Convert.ToInt32(txnID ) > 1)                
                {
                    DialogBox.boxInfo("Completed !");
                }
                else
                {
                    DialogBox.boxWarning("Failed !", "Warning!");
                }

                txtStudentNO.Text = "";
                txtHandsetID.Text = "";
                txtRemark.Text = "";
                txtBarcode.Text = "";
                txtStudentName.Text = "";
                txtIsGraduate.Text = "";
            }
            catch (Exception ex)
            {
                DialogBox.boxWarning("Exception: " + ex.Source + "; " + "Message: " + ex.Message, "Warning!");
            }
            finally
            {
                txtBarcode.Enabled = true;
                txtStudentNO.Enabled = true;

                txtStudentName.Enabled = false;
                txtRemark.Enabled = false;

                btnConfirm.Enabled = true;
            }
        }

        bool IsValidate()
        {
            bool ret = true;
            if (string.IsNullOrEmpty( studentInfo.Barcode))
            {
                DialogBox.boxWarning("Invalid Barcode!", "Warning!");
                txtBarcode.SelectAll();
                ret = false;
            }

            // student id
            if (string.IsNullOrEmpty(studentInfo.StudentNo))
            {
                DialogBox.boxWarning("Invalid Student ID!", "Warning!");
                txtStudentNO.SelectAll();
                ret = false;
            }

            if (string.IsNullOrEmpty(studentInfo.StudentName))
            {
                DialogBox.boxWarning("Invalid Student Name!", "Warning!");

                txtStudentName.SelectAll();
                ret = false;
            }

            // keypad id
            if (studentInfo.Barcode == studentInfo.StudentNo)
            {
                DialogBox.boxWarning("Invalid Handset ID!", "Warning!");
                txtBarcode.SelectAll();
                ret = false;
            }
            return ret;
        }

        bool isStudentCanCheckOut(string studentNo)
        {
            InventoryTxn invTxn = new Presentation.Logic.InventoryTxnActions().CheckStudentStatus(studentNo);
            if (invTxn != null)
            {
                if (invTxn.Status == Presentation.Util.Constants.Status_CheckOut.Id)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            return true;
        }

        bool isHandsetCanCheckOut(string handsetId)
        {
            InventoryTxn invTxn = new Presentation.Logic.InventoryTxnActions().CheckHandsetStatus(handsetId);
            if (invTxn != null)
            {
                if (invTxn.Status == Presentation.Util.Constants.Status_CheckOut.Id)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return true;
        }

        void checkStudentAndStarReceiving()
        {
            if (isStudentCanCheckOut(studentInfo.StudentNo))
            {
                if (Program.ArsAPIHelper.Processing)
                {
                    Program.ArsAPIHelper.StopProcess();
                }

                timer1.Stop();
                btnConfirm.Enabled = false;

                displayCountDown = timer1.Interval / 1000;
                lblCountDown.Text = displayCountDown.ToString();

                timer1.Start();
                lblCountDown.Visible = true;

                Program.ArsAPIHelper.StartProcess();
            }
            else
            {
                //  DialogBox.boxWarning("Check out failed! \r\n\r\nThe student had been Checked-out another handset!", "Warning!");
                // return
            }
        }

        delegate void _dataReceived(object sender, ARSEventArgs e);
        void dataReceiver_DataReceived(object sender, ARSEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new _dataReceived(dataReceiver_DataReceived), sender, e);
                return;
            }

            HandsetData keypadData = (HandsetData)e.ReceivedData;
            switch (keypadData.CommandCode)
            {
                case ARSCommandCode.STUDENT_JOIN:

                    txtHandsetID.Text = keypadData.MacStr;
                    handsetID = keypadData.MacStr;
                    
                    lblCountDown.Text = "";
                    timer1.Stop();
                    Program.ArsAPIHelper.StopProcess();

                    if (isHandsetCanCheckOut(handsetID))
                    {
                        btnConfirm.Enabled = true;
                        txtRemark.Enabled = true;
                        txtRemark.SelectAll();
                    }
                    else
                    {
                        // if handset is check out by another student 
                        //  DialogBox.boxWarning("Check out failed! \r\n\r\nThe Handset had been Checked-out by another student!", "Warning!");
                        // return
                        btnConfirm.Enabled = true;
                        txtRemark.Enabled = false;
                    }

                    break;

                default:
                    break;
            }
        }

        delegate void _handsetRegistry(object sender, ARSRegisterEventArgs e);
        void arsReceiver_HansetRegistry(object sender, ARSRegisterEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new _handsetRegistry(arsReceiver_HansetRegistry), sender, e);
                return;
            }

            bool success = (bool)e.Registered;
            string Id = (string)e.Id;
            if ((bool)e.Registered)
            {
                Program.ArsAPIHelper.StopProcess();

                SaveTxn();
            }
        }
    }
}